package com.ilink.dataanalysis.service.impl;

import com.ilink.dataanalysis.entity.PO.CourseAccessLogInfo;
import com.ilink.dataanalysis.entity.VO.CourseSourceAccessInfo;
import com.ilink.dataanalysis.entity.VO.DailyCourseSourceAccessInfo;
import com.ilink.dataanalysis.mapper.CourseMapper;
import com.ilink.dataanalysis.service.CourseSourceService;
import com.ilink.ilinkcommon.domain.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.data.elasticsearch.core.ElasticsearchAggregations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class CourseSourceServiceImpl implements CourseSourceService {

    private final CourseMapper courseMapper;

    private final ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public R getCourseSourceAccessInfo() {
        try {
            List<DailyCourseSourceAccessInfo> courseSourceAccessInfo = new ArrayList<>();
            LocalDate currentDate = LocalDate.now();
            for (int i = 30; i >= 0; i--) {
                courseSourceAccessInfo.add(getDailyCourseSourceAccessInfo(currentDate.minusDays(i)));
            }
            return R.ok(courseSourceAccessInfo);
        } catch(Exception e) {
            log.info("内部服务器错误：" + e.getMessage());
            return null;
        }
    }

    @Override
    public DailyCourseSourceAccessInfo getDailyCourseSourceAccessInfo(LocalDate date) {
        try {
            // 构建查询
            NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withQuery(QueryBuilders.rangeQuery("event_time")
                            .gte(date.minusDays(1).atStartOfDay())
                            .lt(date.atStartOfDay()))
                    .addAggregation(AggregationBuilders
                            .terms("course_source_ids")
                            .field("course_source_id"))
                    .build();
            // 执行查询并获取结果
            SearchHits<CourseAccessLogInfo> search = elasticsearchRestTemplate.search(searchQuery, CourseAccessLogInfo.class);
            ElasticsearchAggregations aggregations = (ElasticsearchAggregations) search.getAggregations();
            List<CourseSourceAccessInfo> accessInfo = new ArrayList<>();
            if (aggregations != null) {
                // 从 Aggregations 中获取 "course_source_ids" 聚合结果
                ParsedStringTerms courseSourceIdsAgg = aggregations.aggregations().get("course_source_ids");
                if (courseSourceIdsAgg != null) {
                    for (Terms.Bucket bucket : courseSourceIdsAgg.getBuckets()) {
                        Long courseSourceId = Long.valueOf(bucket.getKeyAsString()); // 获取字段值
                        long count = bucket.getDocCount(); // 获取文档数量
                        // 通过 Mapper 获取课程信息
                        Long courseId = courseMapper.getCourseIdByCourseSourceId(courseSourceId);
                        String courseName = courseMapper.getCourseNameByCourseSourceId(courseSourceId);
                        // 构建返回信息
                        accessInfo.add(new CourseSourceAccessInfo(courseSourceId, courseId, courseName, count));
                    }
                }
            }
            return new DailyCourseSourceAccessInfo(accessInfo, date);
        } catch(Exception e) {
            log.info("内部服务器错误：" + e.getMessage());
            return null;
        }
    }
}
